package com.example.common.tools

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.IOException
import java.net.MalformedURLException
import java.net.URL
import java.util.concurrent.TimeUnit

class NetUtil {

    companion object {
        val instance by lazy(LazyThreadSafetyMode.NONE) {
            NetUtil()
        }
    }

    /**
     * 在子线程里开启该方法，可检测当前网络是否能打开网页
     * true是可以上网，false是不能上网
     */
    private fun isOnline(): Boolean {
        val url: URL
        try {
            url = URL("https://www.baidu.com")
            val stream = url.openStream()
            return true
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        } catch (e: IOException) {
//            e.printStackTrace()
            return true
        }

        return false
    }

    fun isNetwork(): Observable<Boolean> {
        return Observable.interval(1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .map { isOnline() }
            .observeOn(AndroidSchedulers.mainThread())

    }

    @SuppressLint("MissingPermission")
    fun isNetworkConnected(context: Context?): Boolean {
        if (context != null) {
            val mConnectivityManager = context
                    .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val mNetworkInfo = mConnectivityManager.activeNetworkInfo
            if (mNetworkInfo != null) {

                //这种方法也可以
                //return mNetworkInfo .getState()== NetworkInfo.State.CONNECTED
                return mNetworkInfo.isAvailable
            }
        }
        return false
    }

}

